home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3166 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Source utilities for endian conversion
  5. Date: Fri, 26 Jan 1996 17:27:25 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <3108F2DD.1039@cmt.lpr.mail.carel.fi>
  8. References: <rt9sph42r1m.fsf@topo.nist.gov>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6a (WinNT; I)
  14.  
  15. Paul J Sullivan wrote:
  16. > I am trying to write a routine (c is not my first language) that will
  17. > allow me to read a binary data file on various platforms. I have
  18. > encountered the -endian problem and, thus, was wondering what routines
  19. > exist to convert between big- and little- formats. Is it possible to
  20. > do this without the conversion i.e. somehow specify a directive?? Is
  21. > it in a FAQ?
  22.  
  23. Basically, the only difference between little and big endian systems is the way 
  24. numbers are stored. For instance, a 16 bit number 0x1234 (hex) in x86 is stored 
  25. into memory at two adjoining locations: 0x34 and 0x12 (in that order, increasing 
  26. memory address). In Motorola, they are stored into two locations as: 0x12 and 
  27. 0x34 (again, in that order). Similarly, a 32 bit value 0x12345678 in x86 would be 
  28. stored: 0x78, 0x56, 0x34, 0x12 and in Motorola: 0x12, 0x34, 0x56, 0x78. So, when 
  29. you read in a 16 bit value stored in another system, you just swap the most and 
  30. least significant bytes (assuming short is 16 bits and long 32):
  31.  
  32.     unsigned short SwapWord(unsigned short w)
  33.     {
  34.         unsigned char    *p = (unsigned char *)&w;
  35.         unsigned char    tmp = p[0];
  36.         p[0] = p[1];
  37.         p[1] = tmp;
  38.         return w;    /* Surprise! bytes swapped :) */
  39.     }
  40.  
  41. And, for 32 bits:
  42.  
  43.     unsigned long    SwapLong(unsigned long l)
  44.     {
  45.         unsigned short    *p = (unsigned short *)&l;
  46.         unsigned short    tmp = SwapWord(p[0]);
  47.         p[0] = SwapWord(p[1]);
  48.         p[1] = tmp;
  49.         return l;
  50.     }
  51.  
  52. Whether the word/long sizes are the same... That's another question. Also, some 
  53. systems _might_ use different floating point formats than others...
  54.  
  55. HTH,
  56. AriL
  57. -- 
  58. All my opinions are mine and mine alone.
  59.